<template>
  <px-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-position="top">
    <px-form-item label="科室" prop="className">
      <px-select v-model="form.className" :disabled="isDisabled" class="w-full" placeholder="请选择科室" filterable>
        <px-option v-for="item in classNameList" :key="item.code" :label="item.name" :value="item.code" />
      </px-select>
    </px-form-item>
    <px-form-item label="规则类型" prop="ruleTypeName">
      <px-input v-model="form.ruleTypeName" maxlength="50" :disabled="isDisabled" />
    </px-form-item>
    <px-form-item label="规则说明" prop="ruleExplain">
      <px-input v-model="form.ruleExplain" type="textarea" maxlength="1000" :disabled="isDisabled" />
    </px-form-item>
  </px-form>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from "vue";
import { PxMessage } from "px-ui";

import { addRuleDesc, updateRuleDesc, getRuleInfo } from "@/api/system/runningStatusSetting/ruleDesc";

import type { PropsTypeForDesc } from "../../type";

const classNameList = JSON.parse(localStorage.getItem("classList"));

const props = defineProps<PropsTypeForDesc>();

const form = ref({
  className: "",
  ruleTypeName: "",
  ruleExplain: ""
});

const rules = reactive({
  className: [{ required: true, message: "请选择科室", trigger: "blur" }],
  ruleTypeName: [{ required: true, message: "请输入规则类型", trigger: "blur" }],
  ruleExplain: [{ required: true, message: "请输入规则说明", trigger: "blur" }]
});
const formRef = ref(null);

const isDisabled = computed(() => {
  if (props.type === "detail") return true;
  return false;
});

if (classNameList.length === 1) {
  form.value.className = classNameList[0].code;
}

const handleSave = () => {
  return new Promise(async (resolve, reject) => {
    if (formRef?.value) {
      const isValid = await formRef.value.validate();
      if (isValid) {
        try {
          if (props.type === "add") {
            await addRuleDesc(form.value);
            PxMessage.success("添加成功");
          } else if (props.type === "edit") {
            const params = {
              id: props.ruleId,
              ...form.value
            };
            await updateRuleDesc(params);
            PxMessage.success("更新成功");
          }
          resolve(true);
        } catch (error) {
          reject(error);
        }
      }
    }
  });
};

const getRuleDescInfo = async () => {
  const res = await getRuleInfo(props.ruleId);
  form.value.className = res.className;
  form.value.ruleTypeName = res.ruleTypeName;
  form.value.ruleExplain = res.ruleExplain;
};

if (props.type !== "add") {
  getRuleDescInfo();
}

defineExpose({
  submit: handleSave
});
</script>

<style lang="scss" scoped></style>
